package com.quicks.beauty.server.web;

import com.quicks.beauty.core.dao.ActivityUserMapper;
import com.quicks.beauty.core.dao.WxUserMapper;
import com.quicks.beauty.core.entity.ActivityExpand;
import com.quicks.beauty.core.entity.ActivityUser;
import com.quicks.beauty.core.entity.WxUser;
import com.quicks.beauty.core.utils.UUIDGenerator;
import com.quicks.beauty.server.common.AjaxResult;
import com.quicks.beauty.server.service.ActivityServices;
import com.quicks.beauty.server.vos.ActiveEntity;
import com.quicks.beauty.server.vos.ActivityUserVo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;

@RestController
@RequestMapping(value = "active")
public class ActivityController extends CommonController {

    @Autowired
    private MongoTemplate template;

    @Autowired
    @Qualifier(value = "redisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    private String userPrefix = "activity";

    @RequestMapping(value = "adds")
    public AjaxResult addActivityUsers(String username, String mobile) {
        AjaxResult results = null;
        ListOperations<String, Object> list = redisTemplate.opsForList();
        ActivityUserVo vo = new ActivityUserVo();
        vo.setId(UUIDGenerator.generate()).setUsername(username)
                .setMobile(mobile).setCreateTime(new Date()).setPoints(0);
        try {
            results = new AjaxResult();
            Long push = list.rightPush(userPrefix + ":user", vo);
            results.setSuccess(true);
        } catch (Exception e) {
            results = AjaxResult.failure("添加失败");
            e.printStackTrace();
        }
        return results;
    }


    @Autowired
    private ActivityServices activityServices;

    @Autowired
    private WxUserMapper wxUserMapper;

    @RequestMapping(value = "expand")
    public AjaxResult getOneExpand(String token, String userId) {
        AjaxResult results = new AjaxResult();
        ActivityExpand expand = activityServices.getOneExpand(token);
        if (expand != null) {
            activityServices.increaseExpand(expand.getId(), 1, userId);
            results.setSuccess(true);
        } else {
            WxUser wxUser = wxUserMapper.selectByPrimaryKey(token);
            if (wxUser == null) {
                results.setSuccess(false);
            } else {
                activityServices.newsIncreaseExpand(UUIDGenerator.generate(), token, 1, userId);
                results.setSuccess(true);
            }
        }
        return results;
    }


    @Autowired
    private ActivityUserMapper activityUserMapper;

    @RequestMapping(value = "add")
    public AjaxResult addActivityUser(String username, String mobile) {
        AjaxResult results = null;
        ActivityUser vo = new ActivityUser();
        vo.setId(UUIDGenerator.generate()).setUsername(username)
                .setMobile(mobile).setCreateTime(new Date());
        try {
            results = new AjaxResult();
            activityUserMapper.insert(vo);
            results.setSuccess(true);
        } catch (Exception e) {
            results = AjaxResult.failure("添加失败");
            e.printStackTrace();
        }
        return results;
    }

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "上传消费凭证")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "上传文件，", paramType = "query", required = true, dataType = "File")
    })
    public AjaxResult upload(HttpServletRequest request) throws IOException {
        AjaxResult results = new AjaxResult();
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = multipartRequest.getFile("file");
            logger.info("上传文件开始,fileName:{}", file.getOriginalFilename());
            String fileType = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            String fullPath = "aumo/" + generateFileName(fileType);
            this.asyncUpload(fullPath, file.getInputStream());
            results.setData(qiNiuConfig.getDomainHost() + fullPath);
            results.setSuccess(true);
        } catch (Exception e) {
            results = new AjaxResult();
            logger.error("上传文件接口异常,{}", e);
            results.setSuccess(false);
            results.setMsg("服务器打盹中...");
        }
        return results;
    }

    @RequestMapping(value = "/submitInfo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "上传消费凭证")
    public AjaxResult formAction(String username, String phone, String[] images) {
        AjaxResult success = AjaxResult.success();

        try {
            ActiveEntity entity = new ActiveEntity();
            entity.setId(UUIDGenerator.generate())
                    .setUsername(username).setPhone(phone)
                    .setImages(Arrays.asList(images))
                    .setCreateTime(new Date().getTime());

            template.insert(entity);
        } catch (Exception es) {

            logger.error("上传文件接口异常,{}", es);
            success.setSuccess(false);
            success.setMsg("服务器打盹中...");

        }
        return success;
    }
}
